package com.study.modules.mini.wxjava;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedissonConfigImpl;
import com.study.Util.SpringUtil;
import com.study.common.BusinessException;
import com.study.config.MiniConfig;
import com.study.vo.WxResponse;
import me.chanjar.weixin.common.error.WxErrorException;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author hupengming
 * @ClassName
 * @Date 2022-11-14 16:47
 * @Version 1.0
 */
public class WxService {

    private MiniConfig miniConfig;
    private SrWxNativeService srWxNativeService;
    private String appid;
    private static final String  CXD_FIRM_WX_KEY_PREFIX = "";

    public WxService(String appid,MiniConfig config) {
        this.appid = appid;
        this.miniConfig = config;
        if(miniConfig.isNative()){
            srWxNativeService = new SrWxNativeService();
            RedissonWxRedisOpsService redisOpsService = SpringUtil.getBean(RedissonWxRedisOpsService.class);
            WxMaRedissonConfigImpl redissonConfig = new WxMaRedissonConfigImpl(redisOpsService.redissonClient(),
                    CXD_FIRM_WX_KEY_PREFIX);
            redissonConfig.setAppid(miniConfig.getAppid());
            redissonConfig.setSecret(miniConfig.getSecret());
            srWxNativeService.setWxMaConfig(redissonConfig);
            srWxNativeService.setAppId(this.appid);
        }
    }

    public WxResponse wxLogin(String code) {
        // 第一种登录方式(native)
        if (miniConfig.isNative()) {
            try {
                WxMaJscode2SessionResult wxMaJscode2SessionResult = srWxNativeService.jsCode2SessionInfo(code);
                if (wxMaJscode2SessionResult == null) {
                    throw new BusinessException("登录微信服务器失败");
                }
                WxResponse wxResponse = new WxResponse();
                wxResponse.setOpenId(wxMaJscode2SessionResult.getOpenid());
                wxResponse.setSessionKey(wxMaJscode2SessionResult.getSessionKey());
                wxResponse.setUnionId(wxMaJscode2SessionResult.getUnionid());
                return wxResponse;
            } catch (WxErrorException e) {
                throw new BusinessException("登录微信服务器失败" + e.getMessage());
            }
        }
        return null;
    }
}
